package dao

import (
	"fmt"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/encoding/gparser"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gtime"
)

var T_hzfgw_para = t_hzfgw_para{}

type t_hzfgw_para struct {
}

func (a *t_hzfgw_para) Exits(addr string) (exits bool, err error) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	model := db.Model("t_hzfgw_para")
	result, error := model.Where(fmt.Sprintf(" addr='%s' ", addr)).Count()
	if error != nil {
		err = error
	} else {
		if result > 0 {
			exits = true
		} else {
			exits = false
		}
	}
	return exits, err
}

func (a *t_hzfgw_para) GetList(where ...string) (list gdb.List, err error) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	model := db.Model("t_hzfgw_para")
	if len(where) == 0 {
	} else {
		model = model.Where(where[0])
	}
	res, err := model.All()
	return res.List(), err
}

func (a *t_hzfgw_para) Save(addr string, fs interface{}) (isOk bool, err error) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	count, err := db.GetCount(" select 0 from t_hzfgw_para where addr='" + addr + "'")
	if err != nil {
		return false, err
	}

	fs_data, _ := gparser.VarToJsonString(fs)

	item := g.Map{
		"addr":     addr,
		"data":     fs_data,
		"lasttime": gtime.Now().String(),
	}

	if count > 0 {

		_, err := db.Model("t_hzfgw_para").Where("addr='" + addr + "'").Update(item)
		if err != nil {
			return false, err
		}
	} else {
		_, err := db.Model("t_hzfgw_para").Where("addr='" + addr + "'").Insert(item)
		if err != nil {
			return false, err
		}
	}
	return true, nil
}
